package artid.com.arttogoa.keeponrecord;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import artid.com.arttogoa.R;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.parser.ArtworkImageUpload;
import artid.com.arttogoa.parser.MicMapBean;
import artid.com.arttogoa.parser.PostionPoint;
import artid.com.arttogoa.parser.UserItem;
import artid.com.arttogoa.swipe.SwipeMenu;
import artid.com.arttogoa.swipe.SwipeMenuCreator;
import artid.com.arttogoa.swipe.SwipeMenuItem;
import artid.com.arttogoa.swipe.SwipeMenuListView;
import artid.com.arttogoa.swipe.SwipeMenuListView.OnMenuItemClickListener;
import artid.com.arttogoa.task.CallbackSky;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.PanelClickListener;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.view.CounterView;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

/**
 * glide,picasso,fresco TODO<请描述这个类是干什么的>
 * 
 * @author 熊彬
 * @data: 2016-6-23 下午2:12:26
 * @version: V1.0
 */
public class MicroscopicMapSelectActivity extends Activity implements
		OnClickListener {
	private static final String TAG = "Browse";
	private Context context;
	private CounterView bv;
	/** 存放标记坐标点的集合 */
	private List<PostionPoint> pointData = new ArrayList<PostionPoint>();
	private ArrayList<MicMapBean> micMapList = new ArrayList<MicMapBean>();
	private RelativeLayout.LayoutParams paramTV = new RelativeLayout.LayoutParams(
			0, 0);
	/** 屏幕中心 */
	private PointF screenCenter = new PointF();
	/** 地图中心 */
	private PointF mapCenter = new PointF();
	private SwipeMenuListView mListView;
	private ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
	private TextView title, commit;
	private String state;
	private String art_id;
	private RequestQueue mSingleQueue;
	private ImageView back;
	// private Bitmap decodeFile(File f){
	// Bitmap b = null;
	// try {
	// BitmapFactory.Options o = new BitmapFactory.Options();
	// o.inJustDecodeBounds = true;
	//
	// FileInputStream fis = new FileInputStream(f);
	// BitmapFactory.decodeStream(fis, null, o);
	// fis.close();
	//
	// int scale = 1;
	// if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
	// scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE /
	// (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
	// }
	//
	// BitmapFactory.Options o2 = new BitmapFactory.Options();
	// o2.inSampleSize = scale;
	// fis = new FileInputStream(f);
	// b = BitmapFactory.decodeStream(fis, null, o2);
	// fis.close();
	// } catch (IOException e) {
	// }
	// return b;
	// }
	/**
	 * 完成
	 */
	Runnable getImTask = new Runnable() {

		@SuppressLint("NewApi")
		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			Log.i("showImage", "loading:" + artwork.getImgdata());
			BitmapFactory.Options bfOptions = new BitmapFactory.Options();
			bfOptions.inDither = false;
			bfOptions.inPurgeable = true;
			bfOptions.inInputShareable = true;
			bfOptions.inTempStorage = new byte[32 * 1024];

			File file = new File(artwork.getImgdata());
			FileInputStream fs = null;
			try {
				fs = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

			try {
				if (fs != null)
					bmp = BitmapFactory.decodeFileDescriptor(fs.getFD(), null,
							bfOptions);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fs != null) {
					try {
						fs.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			Message m = new Message();
			handlerImg.sendMessage(m);
		}
	};
	@SuppressLint("HandlerLeak")
	Handler handlerImg = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// System.out.println("w2=" + bitmap.getWidth() + ",h2="
			// + bitmap.getHeight());
			initData();
		}
	};

	/**
	 * 清除图片内存缓存
	 */
	public void clearImageMemoryCache() {
		try {
			if (Looper.myLooper() == Looper.getMainLooper()) { // 只能在主线程执行
				Glide.get(MicroscopicMapSelectActivity.this).clearMemory();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 清除图片磁盘缓存
	 */
	public void clearImageDiskCache() {
		try {
			if (Looper.myLooper() == Looper.getMainLooper()) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						Glide.get(MicroscopicMapSelectActivity.this)
								.clearDiskCache();
					}
				});
			} else {
				Glide.get(MicroscopicMapSelectActivity.this).clearDiskCache();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// /**
	// * 清除图片所有缓存
	// */
	// public void clearImageAllCache() {
	// clearImageDiskCache();
	// clearImageMemoryCache();
	// deleteFolderFile(ImageExternalCatchDir, true);
	// }
	private void clear() {
		ActivityManager activityManger = (ActivityManager) this
				.getSystemService(ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> list = activityManger
				.getRunningAppProcesses();
		if (list != null)
			for (int i = 0; i < list.size(); i++) {
				ActivityManager.RunningAppProcessInfo apinfo = list.get(i);

				System.out.println("pid            " + apinfo.pid);
				System.out.println("processName              "
						+ apinfo.processName);
				System.out
						.println("importance            " + apinfo.importance);
				String[] pkgList = apinfo.pkgList;

				if (apinfo.importance > ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
					// Process.killProcess(apinfo.pid);
					for (int j = 0; j < pkgList.length; j++) {
						// 2.2以上是过时的,请用killBackgroundProcesses代替
						activityManger.killBackgroundProcesses(pkgList[j]);
					}
				}
			}
	}

	private long getAvailMemory(Context context) {
		// 获取android当前可用内存大小
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		MemoryInfo mi = new MemoryInfo();
		am.getMemoryInfo(mi);
		// mi.availMem; 当前系统的可用内存

		// return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
		return mi.availMem / (1024 * 1024);
	}

	private long getTotalMemory(Context context) {
		String str1 = "/proc/meminfo";// 系统内存信息文件
		String str2;
		String[] arrayOfString;
		long initial_memory = 0;

		try {
			FileReader localFileReader = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(
					localFileReader, 8192);
			str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小

			arrayOfString = str2.split("\\s+");
			for (String num : arrayOfString) {
				Log.i(str2, num + "\t");
			}

			initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
			localBufferedReader.close();

		} catch (IOException e) {

		}
		// return Formatter.formatFileSize(context, initial_memory);//
		// Byte转换为KB或者MB，内存大小规格化
		return initial_memory / (1024 * 1024);
	}

	// private boolean smallst = true;
	private TextView info, info1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.activity_home);
		ArtWorkApp.getInstance().addArtActivity(
				MicroscopicMapSelectActivity.this);
		context = this;
		mSingleQueue = Volley.newRequestQueue(this);
		bv = (CounterView) findViewById(R.id.browseView1);
		title = (TextView) findViewById(R.id.title_text);
		info = (TextView) findViewById(R.id.tv_infoo);
		info1 = (TextView) findViewById(R.id.tv_info);
		commit = (TextView) findViewById(R.id.title_right);
		commit.setVisibility(View.VISIBLE);
		back = (ImageView) findViewById(R.id.back_btn);
		back.setOnClickListener(this);
		title.setText("微观图");
		commit.setText("提交审核");
		commit.setOnClickListener(this);
		Bundle b = getIntent().getExtras();
		System.out.println("系统总内存大小=" + getTotalMemory(context));
		System.out.println("当前可用内存大小=" + getAvailMemory(context));
		userPhone = MySharedPreferences.getMySharedPreferences(
				MicroscopicMapSelectActivity.this).getValue("Phone", "");

		initSwipeMenu();
		clearImageDiskCache();
		clearImageMemoryCache();
		clear();
		onSta();
		System.out.println("清除完缓存可用内存大小=" + getAvailMemory(context));
		artwork = (ArtworkImageUpload) DataKeeper.readSerializable(
				MicroscopicMapSelectActivity.this, ArtworkImageUpload.class);
		AlertUtils.initloadAlertDialog(MicroscopicMapSelectActivity.this,
				MicroscopicMapSelectActivity.this.getWindowManager()
						.getDefaultDisplay().getWidth(), "正在加载完整图...");
		// Glide.with(MicroscopicMapSelectActivity.this).load(new
		// File(artwork.getImgdata()))
		// .crossFade().into(new GlideDrawableImageViewTarget(mImageView) {
		//
		// @Override
		// public void onResourceReady(GlideDrawable drawable,
		// GlideAnimation anim) {
		//
		// super.onResourceReady(drawable, anim);
		// mAttacher.update();
		// // 在这里添加一些图片加载完成的操作
		//
		// }
		// });
		// try {
		// bmp = Glide
		// .with(MicroscopicMapSelectActivity.this)
		// .load(artwork.getImgdata())
		// .asBitmap()
		// // 必须
		// .into(artwork.getDataWidth() / 2,
		// artwork.getDataHeight() / 2).get();
		// bmp = BitmapUtil.create4Bitmap(bmp, true, 2);
		// initData(1);
		// } catch (InterruptedException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// } catch (ExecutionException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// }
		// if (micMapList.size() < 1) {
		// info.setText(R.string.image_kongbai);
		// } else if (micMapList.size() < 3) {
		// info.setText(R.string.image_kongbai1);
		// } else if (micMapList.size() < 3) {
		// info.setText("当前点位数为" + micMapList.size() + "个");
		// }
		try {
			final BitmapFactory.Options options = new BitmapFactory.Options();
			/**
			 * 最关键在此，把options.inJustDecodeBounds = true;
			 * 这里再decodeFile()，返回的bitmap为空 ，但此时调用options.outHeight时，已经包含了图片的高了
			 */
			options.inJustDecodeBounds = true;
			Bitmap bitmap1 = BitmapFactory.decodeFile(artwork.getImgdata(),
					options); // 此时返回的bitmap为null
			System.out.println("w1=" + options.outWidth + ",h1="
					+ options.outHeight);
			Glide.with(MicroscopicMapSelectActivity.this)
					// .load("/system/media/Pre-loaded/Pictures/Picture_06_Trees.jpg")
					//
					// .load("/storage/emulated/0/baidu/searchbox/preset/preset4.2/pic/quick_search_widget_morning.jpg")
					// .load("/storage/emulated/0/YJB/20160630055618.jpg")
					.load(artwork.getImgdata())
					// .load("/storage/emulated/0/Tencent/QQfile_recv/55mb.jpg")
					.asBitmap()
					// .override((int) (options.outWidth / 3),
					// (int) (options.outHeight / 3))
					.diskCacheStrategy(DiskCacheStrategy.NONE)
					.into(new SimpleTarget<Bitmap>() {
						@SuppressLint("NewApi")
						@Override
						public void onResourceReady(Bitmap resource,
								GlideAnimation<? super Bitmap> glideAnimation) {
							AlertUtils.dismiss();
							// if (resource.getHeight() != options.outHeight) {
							// int w = resource.getWidth();
							// int h = resource.getHeight();
							// Matrix matrix = new Matrix();
							// matrix.postScale(3, 3); // 长和宽放大缩小的比例
							// Bitmap resizeBmp = Bitmap.createBitmap(
							// resource, 0, 0, w, h, matrix, true);
							// bmp = resizeBmp;
							// initData(1);
							// return;
							// }
							System.out.println("count="
									+ resource.getByteCount());
							bmp = resource;
							initData();
							initCache();
						}
					});
		} catch (OutOfMemoryError e) {
			// TODO: handle exception
			AlertUtils.dismiss();
			Toast.makeText(context, "图片过大，解析失败", 2).show();
		}
		// new Thread(getImTask).start();
		bv.setOnPanelClickListener(new PanelClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(final PostionPoint p, final int index) {
				// TODO Auto-generated method stub
				// Toast.makeText(MicroscopicMapSelectActivity.this,
				// "index=" + index, 0).show();
				// if (alertDialog == null) {
				strIndex = index;
				alertDialog = AlertUtils.initMicmapAlertDialog(context,
						MicroscopicMapSelectActivity.this.getWindowManager()
								.getDefaultDisplay().getWidth(),
						new OnClickListener() {

							@Override
							public void onClick(View view) {
								// TODO Auto-generated method stub
								switch (view.getId()) {
								case R.id.tv_determine:
									pointData = bv.getPointData();
									pointData.set(
											index,
											new PostionPoint(-p.getPointX(), -p
													.getPointY()));
									System.out.println(pointData.toString());
									MicMapBean mic = new MicMapBean();
									mic.setPf(new PostionPoint(-p.getPointX(),
											-p.getPointY()));
									mic.setId(index);

									Intent intent = new Intent(
											MicroscopicMapSelectActivity.this,
											MicroscopicMapInfoActivity.class);
									Bundle b = new Bundle();
									b.putSerializable("data", mic);
									intent.putExtras(b);
									startActivityForResult(intent, 1);
									alertDialog.dismiss();
									break;
								case R.id.tv_cancel:
									bv.deletePointData(index);
									// pointData.remove(index);
									alertDialog.dismiss();
									break;

								default:
									break;
								}
							}
						});
				// } else {
				// alertDialog.show();
				// }
			}
		});
		// initData();

		registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
				Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
	}

	private String userPhone;
	private int strIndex = -1;
	/**
	 * 监听是否点击了home键将客户端推到后台
	 */
	private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
		String SYSTEM_REASON = "reason";
		String SYSTEM_HOME_KEY = "homekey";
		String SYSTEM_HOME_KEY_LONG = "recentapps";

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
				String reason = intent.getStringExtra(SYSTEM_REASON);
				if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
					// 表示按了home键,程序到了后台
					storageCache();
				} else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
					// 表示长按home键,显示最近使用的程序列表
					storageCache();
				}
			}
		}
	};

	/**
	 * 
	 */
	private void get() {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		onSta();
		switch (resultCode) {
		case 9:
			MicMapBean mic = (MicMapBean) data.getExtras().getSerializable(
					"data");
			micMapList.add(mic);
			adapter.setListData(micMapList);
			System.out.println("pointData.size()=" + pointData.size());
			bv.setPointData(pointData);
			initData();
			strIndex = -1;
			break;
		case 10:
			// NewActivity的返回数据
			micMapList = (ArrayList<MicMapBean>) data.getExtras()
					.getSerializable("data");
			adapter.setListData(micMapList);
			initData();
			break;
		default:
			System.out.println("x=======" + 1);
			if (strIndex >= 0) {
				System.out.println("x=======" + 2);
				bv.deletePointData(strIndex);
				strIndex = -1;
			}
			break;
		}

	}

	CallbackSky call = new CallbackSky() {

		@Override
		public void callBack(int index) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(MicroscopicMapSelectActivity.this,
					MicroscopicMapBrowseActivity.class);
			Bundle b = new Bundle();
			b.putSerializable("data", micMapList);
			intent.putExtras(b);
			startActivityForResult(intent, 2);
		}
	};
	private ArtworkImageUpload artwork;
	private Bitmap bmp;

	/**
	 * 
	 */
	private void initData() {
		// TODO Auto-generated method stub
		// Resources res = getResources();
		// Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.datup);

		// Bitmap bmp = getLoacalBitmap(artwork.getImgdata());
		bv.setis_Editable(true);

		// 任务栏高度
		Rect frame = new Rect();
		bv.getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;
		onSta();
		// 标题栏高度
		int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT)
				.getTop();
		Log.d(TAG, "contentTop===标题栏标题栏高度高度=====" + contentTop);
		// statusBarHeight是上面所求的状态栏的高度
		int titleBarHeight = contentTop - statusBarHeight;
		Log.d(TAG, "titleBarHeight==是上面所求的状态栏的高度 ======" + titleBarHeight);
		int infoHeight = NetUtils.dip2px(context, 78);
		int infoHeightB = NetUtils.dip2px(context, 58) / 2 * 3;
		if (micMapList != null && micMapList.size() > 0) {
			info.setVisibility(View.GONE);
		} else {
			info.setVisibility(View.VISIBLE);
		}
		Log.d(TAG, "infoHeight== 是上面提示文字栏+title的高 ======" + infoHeight);
		@SuppressWarnings("deprecation")
		float x = (this.getWindowManager().getDefaultDisplay().getWidth()) / 2;
		@SuppressWarnings("deprecation")
		float y = (this.getWindowManager().getDefaultDisplay().getHeight()
				- statusBarHeight - titleBarHeight - infoHeight - infoHeightB) / 2;
		paramTV = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);

		paramTV.topMargin = infoHeight;
		paramTV.bottomMargin = infoHeightB;
		bv.setLayoutParams(paramTV);
		/** 屏幕中心的位置坐标 */
		screenCenter.set(x, y);
		/** 地图中心的位置坐标 */
		mapCenter.set(x, y);
		Log.d(TAG, "xxxxxxxxxx====" + x);
		Log.d(TAG, "yyyyyyyyyy====" + y);
		bv.setImageBitmap(bmp, mapCenter, screenCenter);// 设置控件图片
		LayoutParams layoutParams = this.mListView.getLayoutParams();
		layoutParams.height = infoHeightB;
		layoutParams.width = LayoutParams.MATCH_PARENT;
		mListView.setLayoutParams(layoutParams);
	}

	private AlertDialog alertDialog;
	private AppAdapter adapter;

	protected void onSta() {
		// TODO Auto-generated method stub
		super.onStart();
		System.out.println("micMapList.size()=" + micMapList.size());
		if (micMapList.size() < 1) {
			info1.setText("当前还没有取点记录，请长按取点");
		} else if (micMapList.size() > 0 && micMapList.size() < 2) {
			info1.setText("当前点位数少于2，请继续长按取点");
		} else {
			info1.setText("当前点位数为" + micMapList.size() + "个");
		}
	}

	/**
	 * 初始化微观点列表
	 */
	private void initSwipeMenu() {
		// TODO Auto-generated method stub
		//
		mListView = (SwipeMenuListView) findViewById(R.id.listView);
		adapter = new AppAdapter(micMapList);
		mListView.setAdapter(adapter);
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				// SwipeMenuItem openItem = new SwipeMenuItem(
				// getApplicationContext());
				// // set item background
				// openItem.setBackground(new ColorDrawable(Color.rgb(0xC9,
				// 0xC9,
				// 0xCE)));
				// // set item width
				// openItem.setWidth(dp2px(90));
				// // set item title
				// openItem.setTitle("Open");
				// // set item title fontsize
				// openItem.setTitleSize(18);
				// // set item title font color
				// openItem.setTitleColor(Color.WHITE);
				// // add to menu
				// menu.addMenuItem(openItem);

				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				// set item width
				deleteItem.setWidth(NetUtils.dip2px(context, 75));
				// set a icon
				deleteItem.setIcon(R.drawable.ic_delete);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		mListView.setMenuCreator(creator);

		// step 2. listener item click event
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu,
					int index) {
				switch (index) {
				case 0:
					onSta();
					// delete
					bv.deletePointData(position);
					micMapList.remove(position);
					// pointData.remove(position);
					adapter.setListData(micMapList);
					// Toast.makeText(MicroscopicMapSelectActivity.this,
					// "delete" + position, 0).show();

					break;
				}
				return false;
			}
		});
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
				Intent intent = new Intent(MicroscopicMapSelectActivity.this,
						MicroscopicMapBrowseActivity.class);
				Bundle b = new Bundle();
				b.putSerializable("data", micMapList);
				b.putInt("index", index);
				intent.putExtras(b);
				startActivityForResult(intent, 2);
			}
		});
	}

	class AppAdapter extends BaseAdapter {
		private ArrayList<MicMapBean> data;

		/**
		 * 
		 */
		public AppAdapter(ArrayList<MicMapBean> data) {
			// TODO Auto-generated constructor stub
			this.data = data;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		public void setListData(ArrayList<MicMapBean> data) {
			this.data = data;
			notifyDataSetChanged();
		}

		@Override
		public MicMapBean getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(getApplicationContext(),
						R.layout.item_microcosmic_list, null);
				new ViewHolder(convertView);
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
			holder.index.setText((position + 1) + "");
			MicMapBean mic = data.get(position);
			if (mic.getInfo() != null)
				holder.content.setText(mic.getInfo());
			Glide.with(MicroscopicMapSelectActivity.this)
					.load(new File(mic.getImage()))
					.placeholder(R.drawable.yspba_img_mor)
					.error(R.drawable.yspba_img_mor).into(holder.image);
			Glide.with(MicroscopicMapSelectActivity.this)
					.load(new File(mic.getImage200()))
					.placeholder(R.drawable.yspba_img_mor)
					.error(R.drawable.yspba_img_mor).into(holder.image200);
			// holder.image.setImageBitmap(getLoacalBitmap(mic.getImage()));

			return convertView;
		}

		class ViewHolder {
			TextView index, content;
			ImageView image, image200;

			public ViewHolder(View view) {
				content = (TextView) view.findViewById(R.id.tv_content);
				index = (TextView) view.findViewById(R.id.tv_index);
				image = (ImageView) view.findViewById(R.id.iv_mic);
				image200 = (ImageView) view.findViewById(R.id.iv_mic_200);
				view.setTag(this);
			}
		}
	}

	private String getStirng() {
		return null;
	}

	/**
	 * 加载本地图片 http://bbs.3gstdy.com
	 * 
	 * @param url
	 * @return
	 */
	public Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			Bitmap bitmap = BitmapFactory.decodeStream(fis);
			return bitmap;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.title_right:
			String ezssid = MySharedPreferences.getMySharedPreferences(context)
					.getValue(MySharedPreferences.EZSHARE_WIFI, "");
			if (!NetUtils.isNetworkConnected(context)) {
				AlertUtils.initSubmitSumAlertDialog(
						MicroscopicMapSelectActivity.this, "当前网络不可用");
				return;
			}
			if (!TextUtils.isEmpty(ezssid)
					&& NetUtils.getSSID(MicroscopicMapSelectActivity.this)
							.equals(ezssid)) {
				AlertUtils
						.initJudgeOutsideAlertDialog(MicroscopicMapSelectActivity.this);
				return;
			} else if (micMapList.size() < 2) {
				AlertUtils.initSubmitSumAlertDialog(
						MicroscopicMapSelectActivity.this, "至少需要取2个点");
				return;
			}
			storageCache();
			checkSdCard();
			break;

		case R.id.back_btn:
			finish();
			break;
		default:
			break;
		}
	}

	private void checkSdCard() {
		String mac = MySharedPreferences.getMySharedPreferences(context)
				.getValue("mac", "");
		VolleyBasic.getInstance(MicroscopicMapSelectActivity.this).post(false,
				false, Cache.checkSdCard,
				VolleyMap.getInstance().checkSdCard(mac), UserItem.class,
				new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						// System.out.println("第一个============" + vd.getJson());
						UserItem us = (UserItem) vd.getData();
						JSONObject jo = null;
						try {
							jo = new JSONObject(vd.getJson());
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						int state = Integer.parseInt(jo.optJSONObject("data")
								.optString("state"));
						switch (state) {
						case 3:
							AlertUtils.initUploadAlertDialog(
									MicroscopicMapSelectActivity.this,
									MicroscopicMapSelectActivity.this
											.getWindowManager()
											.getDefaultDisplay().getWidth(),
									"正在上传合影及完整图");
							new Thread(networkTask).start();
							break;
						case 1:
						case 2:
							AlertUtils.initSubmitSumAlertDialog(
									MicroscopicMapSelectActivity.this,
									vd.getMsg());
							break;
						case 4:
							AlertUtils.AlertTwoBtnDialog(context, vd.getMsg(),
									"确定", "取消",
									MicroscopicMapSelectActivity.this
											.getWindowManager()
											.getDefaultDisplay().getWidth(),
									new OnClickListener() {

										@Override
										public void onClick(View v) {
											// TODO Auto-generated method stub
											switch (v.getId()) {
											case R.id.tv_ok:
												bindSdCard();
												AlertUtils.dismiss();
												break;
											case R.id.tv_no:
												AlertUtils.dismiss();
												break;

											default:
												break;
											}
										}
									});
							break;
						default:
							break;
						}
					}

					public void onError(VolleyError volleyError) {
						AlertUtils.dismiss();
					}
				});
	}

	private void bindSdCard() {
		String mac = MySharedPreferences.getMySharedPreferences(context)
				.getValue("mac", "");
		VolleyBasic.getInstance(MicroscopicMapSelectActivity.this).post(true,
				true, Cache.bindSdCard,
				VolleyMap.getInstance().checkSdCard(mac), UserItem.class,
				new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						// System.out.println("第一个============" + vd.getJson());
						UserItem us = (UserItem) vd.getData();
						JSONObject jo = null;
						try {
							jo = new JSONObject(vd.getJson());
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						int state = Integer.parseInt(jo.optJSONObject("data")
								.optString("state"));
						switch (state) {
						case 0:
							AlertUtils.initUploadAlertDialog(
									MicroscopicMapSelectActivity.this,
									MicroscopicMapSelectActivity.this
											.getWindowManager()
											.getDefaultDisplay().getWidth(),
									"正在上传合影及完整图");
							new Thread(networkTask).start();
							break;
						case 1:
							Toast.makeText(context, vd.getMsg(), 2).show();
							break;
						default:
							break;
						}
					}

					public void onError(VolleyError volleyError) {
						AlertUtils.dismiss();
					}
				});
	}

	void storageCache() {
		String cache = MySharedPreferences.getMySharedPreferences(
				MicroscopicMapSelectActivity.this).getValue(
				Cache.ART_CACHE + userPhone, "");
		System.out.println("storageCache=" + cache);
		try {
			JSONObject ob = new JSONObject(cache);
			JSONArray arr = new JSONArray();
			for (int i = 0; i < micMapList.size(); i++) {
				JSONObject mic = new JSONObject();
				MicMapBean mb = micMapList.get(i);
				String microgramdata = mb.getImage();
				if (!TextUtils.isEmpty(microgramdata)) {
					mic.put("microgramdata", microgramdata);
				}
				String microgramdatamax = mb.getImage200();
				if (!TextUtils.isEmpty(microgramdatamax)) {
					mic.put("microgramdatamax", microgramdatamax);
				}
				String xcoordinate = String.valueOf(mb.getPf().getPointX());
				if (!TextUtils.isEmpty(xcoordinate)) {
					mic.put("xcoordinate", xcoordinate);
				}
				String ycoordinate = String.valueOf(mb.getPf().getPointY());
				if (!TextUtils.isEmpty(ycoordinate)) {
					mic.put("ycoordinate", ycoordinate);
				}
				String microgram_detail = mb.getInfo();
				if (!TextUtils.isEmpty(microgram_detail)) {
					mic.put("microgram_detail", microgram_detail);
				}
				arr.put(mic);
			}
			ob.put("micMapList", arr);
			System.out.println("storageCache=" + ob.toString());
			MySharedPreferences.getMySharedPreferences(
					MicroscopicMapSelectActivity.this).setValue(
					Cache.ART_CACHE + userPhone, ob.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		storageCache();
		super.onDestroy();
	}

	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	//
	// if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	// // do something...
	// // storageCache();
	// return true;
	// }
	// return super.onKeyDown(keyCode, event);
	// }
	private String cacheBo;

	void initCache() {

		cacheBo = MySharedPreferences.getMySharedPreferences(
				MicroscopicMapSelectActivity.this).getValue(
				Cache.IS_CACHE + userPhone, "false");
		if (Boolean.valueOf(cacheBo)) {
			String cache = MySharedPreferences.getMySharedPreferences(
					MicroscopicMapSelectActivity.this).getValue(
					Cache.ART_CACHE + userPhone, "");
			try {
				JSONObject ob = new JSONObject(cache);
				JSONArray jaa = ob.optJSONArray("micMapList");
				System.out.println(ob.toString());
				if (jaa != null && jaa.length() > 0) {

					for (int i = 0; i < jaa.length(); i++) {
						JSONObject mic = jaa.optJSONObject(i);
						MicMapBean mb = new MicMapBean();
						String microgramdata = mic.optString("microgramdata");
						if (!TextUtils.isEmpty(microgramdata)) {
							mb.setImage(microgramdata);
						}
						String microgramdatamax = mic
								.optString("microgramdatamax");
						if (!TextUtils.isEmpty(microgramdatamax)) {
							mb.setImage200(microgramdatamax);
						}
						String xcoordinate = mic.optString("xcoordinate");
						String ycoordinate = mic.optString("ycoordinate");
						if (!TextUtils.isEmpty(xcoordinate)
								&& !TextUtils.isEmpty(ycoordinate)) {
							mb.setPf(new PostionPoint(Integer
									.parseInt(xcoordinate), Integer
									.parseInt(ycoordinate)));
						}
						String microgram_detail = mic
								.optString("microgram_detail");
						if (!TextUtils.isEmpty(microgram_detail)) {
							mb.setInfo(microgram_detail);
						}
						micMapList.add(mb);
						pointData.add(new PostionPoint(mb.getPf().getPointX(),
								mb.getPf().getPointY()));
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			adapter.setListData(micMapList);
			bv.setInitPointData(bmp, mapCenter, screenCenter, pointData);
		}
	}

	private final int TYPE_COM = 1;
	private final int TYPE_MIC = 2;
	private final int TYPE_WANCHENG = 3;
	private long imageIengh;
	/**
	 * 上传合影完整图
	 */
	Runnable networkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			String uri = Cache.upload;
			Map<String, String> params = new HashMap<String, String>();
			params.put("token", AppUtil.getUser().getToken());
			params.put("art_type", "1");
			params.put("is_file", "2");
			params.put("title", artwork.getTitle());
			params.put("realname", artwork.getRealname());
			params.put("width", artwork.getWidth());
			params.put("height", artwork.getHeight());
			params.put("age", artwork.getAge());
			params.put("detail", artwork.getDetail());
			params.put("gphoto_detail", artwork.getGphoto_detail());
			Map<String, File> files = new HashMap<String, File>();
			files.put("gphotodata", new File(artwork.getGphotodata()));
			files.put("imgdata", new File(artwork.getImgdata()));
			files.put("inscribeimg", new File(artwork.getInscribeimg()));
			imageIengh = artwork.getLengh();
			try {
				String Response = post(uri, params, files, TYPE_COM, -1);
				if (TextUtils.isEmpty(Response)) {
					Message m = new Message();
					m.what = -1;
					handler.sendMessage(m);
					return;
				}
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putString("value", Response);
				data.putInt("type", TYPE_COM);
				msg.setData(data);
				msg.what = 1;
				handler.sendMessage(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};
	/**
	 * 上传微观图
	 */
	Runnable micNetworkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			for (int i = 0; i < micMapList.size(); i++) {
				MicMapBean mb = micMapList.get(i);
				Map<String, File> files = new HashMap<String, File>();
				files.put("microgramdata", new File(mb.getImage()));
				files.put("microgramdatamax", new File(mb.getImage200()));

				Map<String, String> params = new HashMap<String, String>();
				params.put("token", AppUtil.getUser().getToken());
				params.put("art_id", art_id);
				params.put("is_file", "2");
				params.put("imgtype", mb.getImgtype());
				params.put("number", (i + 1) + "");
				params.put("microgram_detail", mb.getInfo());
				params.put("xcoordinate", mb.getPf().getPointX() + "");
				params.put("ycoordinate", mb.getPf().getPointY() + "");

				String uri = Cache.uploadMicrogram;
				try {
					String Response = post(uri, params, files, TYPE_MIC, i);
					if (TextUtils.isEmpty(Response)) {
						Message m = new Message();
						m.what = -1;
						handler.sendMessage(m);
						break;
					}
					Message msg = new Message();
					Bundle data = new Bundle();
					data.putString("value", Response);
					data.putInt("type", TYPE_MIC);
					data.putInt("index", i);
					msg.setData(data);
					msg.what = 1;
					handler.sendMessage(msg);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}
	};

	/**
	 * 完成
	 */
	Runnable comNetworkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			String uri = Cache.saveartRecord;
			Map<String, String> params = new HashMap<String, String>();
			params.put("token", AppUtil.getUser().getToken());
			params.put("art_id", art_id);
			try {
				String Response = post(uri, params, null, TYPE_WANCHENG, -1);
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putString("value", Response);
				data.putInt("type", TYPE_WANCHENG);
				msg.setData(data);
				msg.what = 3;
				handler.sendMessage(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};

	public String post(String url, Map<String, String> params,
			Map<String, File> files, int type, int index) throws IOException {
		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";
		URL uri = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(120 * 1000); // 缓存的最长时间
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Accept",
				"application/json, text/javascript, */*");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);
		conn.setChunkedStreamingMode(1024);
		// 首先组拼文本类型的参数
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + LINEND);
			// sb.append("Content-Type: text/plain; charset=" + CHARSET +
			// LINEND);
			// sb.append("Content-Transfer-Encoding: utf-8" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}
		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());

		outStream.write(sb.toString().getBytes());
		// 发送文件数据
		int length = 0;
		if (files != null)
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\""
						+ file.getKey() + "\"; filename=\""
						+ file.getValue().getName() + "\"" + LINEND);
				// sb1.append("Content-Type: application/octet-stream; charset="
				// + CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());

				InputStream is = new FileInputStream(file.getValue());
				long total = is.available();
				System.out.println("图片的data大小==============" + total);
				byte[] buffer = new byte[1024];
				int len = 0;

				while ((len = is.read(buffer)) != -1) {

					outStream.write(buffer, 0, len);
					length += len;
					if (type == TYPE_COM) {
						Message msg = new Message();
						msg.what = 2;
						msg.obj = (int) ((length / (float) imageIengh) * 100);
						handler.sendMessage(msg);
					} else if (type == TYPE_MIC) {
						Message msg = new Message();
						msg.what = 2;
						msg.obj = (int) ((length / (float) total) * 100);
						handler.sendMessage(msg);
					}
				}
				is.close();
				outStream.write(LINEND.getBytes());

			}
		System.out.println(outStream.toString());
		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();
		// 得到响应码
		StringBuilder sb2 = null;
		try {
			int res = conn.getResponseCode();
			InputStream in = conn.getInputStream();
			sb2 = new StringBuilder();
			if (res == 200) {
				int ch;
				while ((ch = in.read()) != -1) {
					sb2.append((char) ch);
				}
			}
		} catch (SocketTimeoutException e) {
			// TODO: handle exception
			e.printStackTrace();

			return "";
		}

		outStream.close();
		conn.disconnect();
		return sb2.toString();
	}

	/**
	 * 确认提交申请备案
	 */
	private void comNetwork() {

		// TODO Auto-generated method stub
		String uri = Cache.saveartRecord;
		// System.out.println("params=" + params.toString());

		VolleyBasic.getInstance(MicroscopicMapSelectActivity.this).post(false,
				false, uri, VolleyMap.getInstance().saveartRecord(art_id),
				UserItem.class, new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						AlertUtils.dismiss();
						// TODO
						// Auto-generated
						// method stub
						Log.i("my上传3", "请求结果3为-->" + vd.getJson());
						try {
							JSONObject jo = new JSONObject(vd.getJson());
							if (jo.optString("ret").equals("1")) {
								// String
								// state
								// =
								// jo.optJSONObject("data").optString(
								// "state");

								MySharedPreferences.getMySharedPreferences(
										context).setValue(Cache.artIsLoad,
										"yes");
								Toast.makeText(
										MicroscopicMapSelectActivity.this,
										"上传成功！", 2).show();
								ArtWorkApp.getInstance().artExit();
							} else {
								Toast.makeText(
										MicroscopicMapSelectActivity.this,
										jo.optString("msg") + " ", 2).show();
							}

						} catch (JSONException e) {
							// TODO
							// Auto-generated
							// catch
							// block
							e.printStackTrace();
						}
					}

					public void onError(VolleyError volleyError) {
						AlertUtils.dismiss();
					}
				});
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				Bundle data = msg.getData();
				String val = data.getString("value");
				int type = data.getInt("type");
				if (!TextUtils.isEmpty(val)) {
					val = val.substring(val.indexOf("{"),
							val.lastIndexOf("}") + 1);
					val = NetUtils.decodeUnicode(val);
					Log.i("mylog", "请求结果为-->" + val);
					try {
						JSONObject jo = new JSONObject(val);
						if (jo.optString("ret").equals("1")) {
							if (type == TYPE_COM) {
								state = jo.optJSONObject("data").optString(
										"state");
								art_id = jo.optJSONObject("data").optString(
										"art_id");
								Log.e("com", "完整图落款合影图上传成功");
								AlertUtils.setText("正在提交第1个微观图及描述信息");
								new Thread(micNetworkTask).start();
							} else if (type == TYPE_MIC) {
								int index = data.getInt("index");
								// Log.e("mic" + oi, "图片" + oi + "上传成功");
								if (state.equals("1")) {
									if (index == micMapList.size() - 1) {
										MySharedPreferences
												.getMySharedPreferences(context)
												.setValue(Cache.artIsLoad,
														"yes");
										MySharedPreferences
												.getMySharedPreferences(context)
												.setValue(Cache.ART_ID, art_id);
										// MySharedPreferences
										// .getMySharedPreferences(context)
										// .setValue(Cache.ARTREC_STATUS,
										// "yes");
										System.out.println("开始请求接口3");
										new Thread(comNetworkTask).start();
										// login();
										// comNetwork();
										// comNetwork();
										// MultiPart(uri, null, params,
										// mMicListenerString,
										// mErrorListener, null);
									} else {
										AlertUtils.setText("正在提交第"
												+ (index + 2) + "个微观特征信息");
									}
								} else {
									System.out.println("state=" + state);
								}
							}
							// Intent intent = new Intent(
							// UploadCompleteGraphActivity.this,
							// MicroscopicMapSelectActivity.class);
							// Bundle b = new Bundle();
							// b.putString("state", state);
							// b.putString("art_id", art_id);
							// b.putString("imgUrl",
							// "/storage/emulated/0/zapya/photo/20150127_1033/IMG20141115140855.jpg");
							// intent.putExtras(b);
							// startActivity(intent);
						} else {
							Toast.makeText(MicroscopicMapSelectActivity.this,
									jo.optString("msg") + " ", 2).show();
							AlertUtils.dismiss();
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					Toast.makeText(context, "无响应！", 2).show();
				}
				break;
			case 2:
				int i = (Integer) msg.obj;
				AlertUtils.setProgressBar(i);
				break;
			case -2:
				MySharedPreferences.getMySharedPreferences(context).setValue(
						Cache.artIsLoad, "yes");
				// Toast.makeText(MicroscopicMapSelectActivity.this,
				// "上传成功！", 2).show();
				AlertUtils.dismiss();
				if (Boolean.valueOf(cacheBo)) {
					Intent intent = new Intent(
							MicroscopicMapSelectActivity.this,
							ArtRecordActivity.class);
					startActivity(intent);
				}
				ArtWorkApp.getInstance().artExit();
				break;
			case -1:
				ToastUtil
						.toast(MicroscopicMapSelectActivity.this, "连接超时，请重新请求");
				AlertUtils.dismiss();
				break;
			case 3:
				Bundle bd = msg.getData();
				String req = bd.getString("value");
				// AlertUtils.dismiss();
				if (!TextUtils.isEmpty(req)) {
					Log.i("mylog1", "请求结果为12-->" + req);
					req = req.substring(req.indexOf("{"),
							req.lastIndexOf("}") + 1);
					req = NetUtils.decodeUnicode(req);
					Log.i("mylog2", "请求结果为13-->" + req);
					JSONObject jo;
					try {
						JSONObject json = new JSONObject(req);
						if (json.optString("ret").equals("1")) {
							// String state =
							// jo.optJSONObject("data").optString(
							// "state");
							AlertUtils.setUploadImage(true);

							// Map<String, String> params = new
							// HashMap<String, String>();
							// params.put("token", AppUtil.getUser()
							// .getToken());
							// params.put("art_id", art_id);
							Handler handler1 = new Handler();
							handler1.postDelayed(new Runnable() {
								@Override
								public void run() {
									Message msg = new Message();
									msg.what = -2;
									handler.sendMessage(msg);
								}
							}, 2000);

						} else {
							Toast.makeText(MicroscopicMapSelectActivity.this,
									json.optString("msg") + " ", 2).show();
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					Toast.makeText(context, "无响应！", 2).show();
					AlertUtils.dismiss();
				}
				break;

			default:
				break;
			}

			// TODO
			// UI界面的更新等相关操作
		}
	};

}
